import os
import numpy as np
import config
import face_recognition
import cv2

face_data = {}


# 加载已知人脸的编码
def load_known_face_encodings():
    for file in os.listdir(config.UPLOAD_FOLDER):
        if file.endswith(".npy"):
            encoding_path = os.path.join(config.UPLOAD_FOLDER, file)
            face_encoding = np.load(encoding_path)
            name = os.path.splitext(file)[0]
            face_data[name] = face_encoding  # 将姓名作为键，人脸特征作为值存储到字典中


# 标记图像中的人脸
def mark_faces_in_image(image):
    # 使用face_recognition库来找到图像中的人脸
    face_locations = face_recognition.face_locations(image)
    # 遍历每个人脸位置，并在图像上画出矩形框
    for (top, right, bottom, left) in face_locations:
        # 画出人脸区域矩形框
        cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2)
    return image


# 获取图片中得人脸特征(TODO 选出图像中最大的人脸)
def get_face_encodings(image):
    # 使用face_recognition库来找到图像中的人脸并提取特征值
    face_locations = face_recognition.face_locations(image)
    # 如果没有检测到人脸，直接返回None
    if not face_locations:
        return None
    face_encodings = face_recognition.face_encodings(image, face_locations)
    # 返回第一个人脸的特征编码，或者如果没有检测到人脸则返回None
    return face_encodings[0] if face_encodings else None


# 新增：只获取人脸位置，不进行编码计算
def get_face_locations(image):
    """只获取人脸位置，用于性能优化"""
    return face_recognition.face_locations(image)


# 新增：基于已知位置获取人脸编码
def get_face_encodings_from_locations(image, face_locations):
    """基于已知的人脸位置获取编码，避免重复计算"""
    if not face_locations:
        return None
    face_encodings = face_recognition.face_encodings(image, face_locations)
    return face_encodings if face_encodings else None


# 比较上传的人脸与已知人脸，返回置信度最高的人脸
def compare_faces(face_encoding):
    if not face_data:
        print("face_data 为空，无法进行识别")
        return None, None
    
    known_face_encodings = list(face_data.values())
    known_face_names = list(face_data.keys())
    
    print(f"比较人脸: 已知人脸数量={len(known_face_names)}, 已知人脸={known_face_names}")
    
    face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
    best_match_index = np.argmin(face_distances)
    best_match_name = known_face_names[best_match_index]
    best_match_distance = face_distances[best_match_index]
    
    print(f"距离计算结果: {face_distances}")
    print(f"最佳匹配: {best_match_name}, 距离: {best_match_distance}")
    
    return best_match_name, best_match_distance
